package fi.foyt.cs.persistence.dao.task;

import javax.persistence.EntityManager;
import fi.foyt.cs.persistence.dao.GenericDAO;
import fi.foyt.cs.persistence.domainmodel.task.GeneralTask;
import fi.foyt.cs.persistence.domainmodel.task.TaskType;

public class GeneralTaskDAO extends GenericDAO<GeneralTask> {

  public GeneralTask create(TaskType taskType, Long localeElementId, String icon) {
    EntityManager entityManager = getEntityManager();

    entityManager.getTransaction().begin();
    try {
      GeneralTask generalTask = new GeneralTask();
      generalTask.setTaskType(taskType);
      generalTask.setLocaleElementId(localeElementId);
      generalTask.setIcon(icon);
      entityManager.persist(generalTask);
      entityManager.getTransaction().commit();
      return generalTask;
    } finally {
      if (entityManager.getTransaction().isActive())
        entityManager.getTransaction().rollback();
    }
  }
  
  public GeneralTask updateName(GeneralTask generalTask, Long localeElementId) {
    EntityManager entityManager = getEntityManager();

    entityManager.getTransaction().begin();
    try {
      generalTask.setLocaleElementId(localeElementId);
      generalTask = entityManager.merge(generalTask);
      entityManager.getTransaction().commit();

      return generalTask;
    } finally {
      if (entityManager.getTransaction().isActive())
        entityManager.getTransaction().rollback();
    }
  }
  
  public GeneralTask updateIcon(GeneralTask generalTask, String icon) {
    EntityManager entityManager = getEntityManager();

    entityManager.getTransaction().begin();
    try {
      generalTask.setIcon(icon);
      generalTask = entityManager.merge(generalTask);
      entityManager.getTransaction().commit();

      return generalTask;
    } finally {
      if (entityManager.getTransaction().isActive())
        entityManager.getTransaction().rollback();
    }
  }

  public GeneralTask updateTaskType(GeneralTask generalTask, TaskType taskType) {
    EntityManager entityManager = getEntityManager();

    entityManager.getTransaction().begin();
    try {
      generalTask.setTaskType(taskType); 
      generalTask = entityManager.merge(generalTask);
      entityManager.getTransaction().commit();
      
      return generalTask;
    } finally {
      if (entityManager.getTransaction().isActive())
        entityManager.getTransaction().rollback();
    }
  }
  
}
